<template>
    <div class="card" style="width:400px;margin-top:100px;">
        <el-form ref="formRef" :rules="data.rules" :model="data.form">
            <el-form-item label="原密码" prop="password">
                <el-input show-password v-model="data.form.password" autocomplete="off" placeholder="请输入原密码"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
                <el-input show-password v-model="data.form.newPassword" autocomplete="off" placeholder="请输入新密码"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
                <el-input show-password v-model="data.form.confirmPassword" autocomplete="off" placeholder="请输入确认密码"></el-input>
            </el-form-item>
            <div style="text-align:center;">
                <el-button @click="updatePassword" type="primary">更新密码</el-button>
            </div>
        </el-form>
    </div>
</template>
<script setup>
    import router from '@/router';
import { reactive,ref } from 'vue'
import request from '@/utils/request';
    const formRef = ref()
    const validatePass = (rule,value,callback)=>{
        if(!value){
            callback(new Error("请再次确认密码"))
        }else if(value !== data.form.newPassword){
            callback(new Error("两次密码输入不一致"))
        }else{
            callback()
        }
    }
    const data = reactive({
        user: JSON.parse(localStorage.getItem('x-user')),
        form:{},
        rules:{
            password:[
                {required:true,message:"请输入原密码",trigger:'blur'}
            ],
            newPassword:[
                {required:true,message:"请输入新密码",trigger:'blur'}
            ],
            confirmPassword:[
                {validator:validatePass,trigger:'blur'}
            ],
        }
    })

    

    const updatePassword=()=>{
        data.form.id = data.user.id
        formRef.value.validate((valid)=>{
            if(valid){
                request.put('/system/user/updatePassword',data.form).then(res=>{
                    if(res.code===0){
                        ElMessage.success("更新成功")
                        localStorage.removeItem('x-user')
                        setTimeout(()=>{
                            router.push("/login")
                        },500)
                        
                    }else{
                        ElMessage.error(res.message)
                    }
                })
            }
        })
        
    }
</script>